package com.example.locationreport.locationreport.service;

import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.example.locationreport.locationreport.CrashApplication;
import com.example.locationreport.locationreport.bean.UpdateBean;
import com.example.locationreport.locationreport.global.Constant;
import com.example.locationreport.locationreport.global.ConstantInfo;
import com.example.locationreport.locationreport.utils.LogLocationUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.io.DataOutputStream;
import java.io.File;
import java.text.DecimalFormat;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DownAPKService extends Service {

    private static final String TAG = DownAPKService.class.getSimpleName();

    // 文件保存路径(如果有SD卡就保存SD卡,如果没有SD卡就保存到手机包名下的路径)
    private String APK_dir;
    private String destFileName;
    private UpdateBean mUpdateBean;

    @Override
    public void onCreate() {
        super.onCreate();
        initApkDir();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void initApkDir() {
        APK_dir = Environment.getExternalStorageDirectory() + "/LocationApk/";
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 接收Intent传来的参数:

        // 文件下载路径
        mUpdateBean = (UpdateBean) intent.getExtras().getSerializable(Constant.INFO);

        destFileName = "Location_" + mUpdateBean.getVersion() + ".apk";

        DownFile(mUpdateBean.getUrl());

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * @param download_url 下载链接
     */
    private void DownFile(String download_url) {
        LogLocationUtils.writeLog(TAG, "Apk下载地址:" + download_url);

        OkGo.<File>get(download_url)
                .execute(new FileCallback(APK_dir, destFileName) {
                    @Override
                    public void onSuccess(Response<File> response) {
                        LogLocationUtils.writeLog(TAG, "--Apk下载完成--");
                        installApk();
                    }

                    @Override
                    public void onStart(Request<File, ? extends Request> request) {
                        super.onStart(request);
                        LogLocationUtils.writeLog(TAG, "--Apk下载开始--");
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        // 给Handler发送信息更新进度条
                        int x = (int) (progress.fraction * 100);
                        int totalS = 100;
                        LogLocationUtils.writeLog(TAG, "--Apk下载进度:" + getPercent(x, totalS));
                    }

                    @Override
                    public void onError(Response<File> response) {
                        LogLocationUtils.writeLog(TAG, "--Apk下载失败:" + response.body());
                    }
                });
    }

    /**
     * 安装Apk
     */
    private void installApk() {
        LogLocationUtils.writeLog(TAG, "--开始安装最新apk包--");
        try {
            // 如果已经下载完毕跳出循环
            File file = new File(APK_dir + destFileName);
            if (!file.exists()) {
                LogLocationUtils.writeLog(TAG, "APK文件不存在: " + file.getAbsolutePath());
                return;
            }
            Uri apkUri = Uri.fromFile(file);
            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                startActivity(installIntent);
            } catch (ActivityNotFoundException e) {
                // 处理无安装器的情况
                LogLocationUtils.writeLog(TAG, "--处理无安装器的情况--" + e.getMessage());
            }
            Intent intent = new Intent(Constant.AppUpdateBroadcastAction);
            intent.putExtra(Constant.AppUpdatePath, APK_dir + destFileName);
            //调用Context的sendBroadcast()方法，将广播发送出去。所有监听这条广播的接收器就都会接收到这条广播。
            sendBroadcast(intent);
        } catch (Exception e) {
            Logger.getLogger(TAG).log(Level.INFO, "--安装步骤整体报错--" + e.getMessage());
        }
    }

    /**
     * @param x     当前值
     * @param total 总值
     *              [url=home.php?mod=space&uid=7300]@return[/url] 当前百分比
     * @Description 返回百分之值
     */
    private String getPercent(int x, int total) {
        String result;// 接受百分比的值
        double x_double = x * 1.0;
        double tempResult = x_double / total;
        // 百分比格式，后面不足2位的用0补齐 ##.00%
        DecimalFormat df1 = new DecimalFormat("0.00%");
        result = df1.format(tempResult);
        return result;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
    }
}
